package org.aurora.remote.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.aurora.remote.protocol.RemoteCommand;
import org.aurora.remote.protocol.RemoteSerializableUtil;

import java.nio.ByteBuffer;

@ChannelHandler.Sharable
public class NettyEncoder extends MessageToByteEncoder<RemoteCommand> {

    private volatile static NettyEncoder instance = null;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RemoteCommand remoteCommand, ByteBuf byteBuf) throws Exception {
        ByteBuffer byteBuffer = RemoteSerializableUtil.serialize(remoteCommand);

        if (byteBuffer != null) {
            byteBuf.writeBytes(byteBuffer); // todo 这样写和通过 channelHandlerContext.writeAndFlush() 写有什么区别？
        }
    }


    public static NettyEncoder getInstance() {
        if (NettyEncoder.instance == null) {
            synchronized (NettyEncoder.class) {
                if (NettyEncoder.instance == null) {
                    NettyEncoder.instance = new NettyEncoder();
                }
            }
        }
        return NettyEncoder.instance;
    }
}
